package registe_router_handle

import (
	"github.com/kataras/iris/v12"
	"goServer/models"
	"strconv"
)

// return json model part
type Quiz struct {
	/*
		CompanyId   uint   `gorm:"type:int(10);not null;"`
		Speaker     string `gorm:"type:varchar(20);not null;"`
		CompanyName string `gorm:"type:varchar(20);not null;"`
		Scale       string `gorm:"type:varchar(20);not null;"`
		LogoPath    string `gorm:"type:varchar(20);not null;"`
		Total       int    `gorm:"type:int(10);not null;"`
			rewrite it to json model:
	*/
	CompanyId   uint   `json:"company_id"`
	Speaker     string `json:"speaker"`
	CompanyName string `json:"company_name"`
	Scale       string `json:"scale"`
	LogoPath    string `json:"logo_path"`
	Total       uint   `json:"total"`
}

type AddStatus struct {
	Status string `json:"status"`
}

type QuizInfo struct {
	QuizInfo []Quiz `json:"quiz_info"`
}

type Line struct {
	/*
		Content      string      `gorm:"type:varchar(512);not null;"`
		Status       string      `gorm:"type:varchar(20);not null;"`
		StudentName    uint        `gorm:"type:int(10);not null;"`
	*/
	Content     string `json:"content"`
	StudentName string `json:"student_name"`
	Status      string `json:"status"`
}

type Query struct {
	Qid         int    `json:"qid"`
	AskOrAnswer []Line `json:"ask_or_answer"`
}

type QuizDetail struct {
	QuizDetail []Query `json:"quiz_detail"`
}

// init part
func Init_Quiz() {
	// GET localhost:8080/quiz?keyword=xxx
	// 给定关键词，返回所有包含关键词的企业会话
	RouterHandles = append(RouterHandles, RouterHandle{
		Method: "GET",
		Router: "/quiz",
		Handler: func(ctx iris.Context) {
			keyword := ctx.URLParam("keyword")

			res := quizFindAll(keyword)

			ctx.ContentType("application/json")
			ctx.JSON(res)
		},
	})

	// GET localhost:8080/quiz/company?companyid=xxx
	// 给定企业id，返回该企业的所有会话
	RouterHandles = append(RouterHandles, RouterHandle{
		Method: "GET",
		Router: "/quiz/company",
		Handler: func(ctx iris.Context) {
			ci := ctx.URLParam("companyid")

			res := quizCompanyFindAll(ci)

			ctx.ContentType("application/json")
			ctx.JSON(res)
		},
	})

	// POST localhost:8080/quiz/add?companyid=xxx&speaker=xxx&openid=xxx
	// POST给定企业id和学生id，添加一条会话,内容在被POST的body中
	RouterHandles = append(RouterHandles, RouterHandle{
		Method: "POST",
		Router: "/quiz/add",
		Handler: func(ctx iris.Context) {
			db, err := models.GetDBOnly()
			if err != nil {
				ctx.JSON(&AddStatus{Status: "fail not get db"})
				panic(err)
			}

			cid := ctx.URLParam("companyid")
			speaker := ctx.URLParam("speaker")
			sid := ctx.URLParam("openid")
			// 转为uint32
			cidUint, err := strconv.ParseUint(cid, 10, 32)
			if err != nil {
				ctx.JSON(&AddStatus{Status: "fail"})
				panic(err)
			}

			sidUint, err := strconv.ParseUint(sid, 10, 32)
			if err != nil {
				ctx.JSON(&AddStatus{Status: "fail"})
				panic(err)
			}

			// get body
			var body map[string]interface{}
			err1 := ctx.ReadJSON(&body)
			if err1 != nil {
				ctx.JSON(&AddStatus{Status: "fail"})
				panic(err1)
			}

			// add into db
			resp := db.Create(&models.Discussions{
				CompanyId: uint(cidUint),
				Speaker:   speaker,
			})

			// 通过resp获取Disscussion的id
			did := resp.Statement.Dest.(models.Discussions).ID

			db.Create(&models.Queries{
				DiscussionID: did,
				OpenId:       uint(sidUint),
				Content:      body["content"].(string),
				Status:       "ask",
			})

			ctx.ContentType("application/json")
			ctx.JSON(&AddStatus{Status: "success"})
		},
	})

	//RouterHandles = append(RouterHandles, RouterHandle{
	//	Method: "GET",
	//	Router: "/quiz/detail",
	//	Handler: func(ctx iris.Context) {
	//		keyword := ctx.URLParam("keyword")
	//
	//		res := quizFindAll(keyword)
	//
	//		ctx.ContentType("application/json")
	//		ctx.JSON(res)
	//	},
	//})
}

// deal data part (return json model)
func quizFindAll(keyword string) QuizInfo {
	db, err := models.GetDBOnly()
	if err != nil {
		panic(err)
	}

	var quizs QuizInfo
	if keyword == "" {
		db.Raw("SELECT company_id, speaker, company_name, scale, logo_path, COUNT(*) AS total FROM discussions,companies WHERE company_id=companies.id GROUP BY company_id,speaker,company_name,scale,logo_path").Scan(&quizs.QuizInfo)
	} else {
		db.Raw("SELECT company_id, speaker, company_name, scale, logo_path, COUNT(*) AS total FROM discussions,companies WHERE company_name LIKE ? AND company_id=companies.id GROUP BY company_id,speaker,company_name,scale,logo_path", "%"+keyword+"%").Scan(&quizs.QuizInfo)
	}

	// return res
	return quizs
}

func quizCompanyFindAll(ci string) QuizDetail {
	db, err := models.GetDBOnly()
	if err != nil {
		panic(err)
	}

	// 构造返回的json
	var quizs QuizDetail
	db.Raw("SELECT id AS qid FROM discussions WHERE company_id=", "%"+ci+"%").Scan(&quizs)

	for i := 0; i < len(quizs.QuizDetail); i++ {
		db.Raw("SELECT content, status, student_name FROM queries,students WHERE company_id=? AND students.id=student_id", "%"+strconv.Itoa(quizs.QuizDetail[i].Qid)+"%").Scan(&quizs.QuizDetail[i].AskOrAnswer)
	}

	// return res
	return quizs

}
